﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IndoReputation.Models.BusinessLogic;
using Telerik.Web.Mvc;
using IndoReputation.Models.BusinessObject;
using IndoReputation.Views.ViewModels;
using System.IO;

namespace IndoReputation.Controllers
{
    [Authorize]
    public class CountryController : BaseController
    {
        //
        // GET: /Country/

        public ActionResult Index()
        {
            ViewData["ajax"] = true;
            ViewData["scrolling"] = true;
            ViewData["paging"] = true;
            ViewData["filtering"] = true;
            ViewData["grouping"] = true;
            ViewData["sorting"] = true;
            ViewData["showFooter"] = true;
            return View();
            //CountryBOL.GetAllCountryJoin()
        }

        [GridAction]
        public ActionResult _Index()
        {
            return View(new GridModel(CountryBOL.GetAllCountryJoin()));
        }

        [HttpGet]
        public ActionResult Add()
        {
            var region = RegionBOL.GetAllRegion();
            var organization = OrganizationBOL.GetAllOrganization();
            var dialogPartner = DialogPartnerBOL.GetAllDialogPartner();
            var model = new CountryViewModel
            {
                Region = new SelectList(region, "ID", "Name"),
                Organization = new SelectList(organization, "ID", "Name"),
                DialogPartner = new SelectList(dialogPartner, "ID", "Name")
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult Add(CountryViewModel model)
        {
            if (ModelState.IsValid)
            {
                Country country = new Country
                {
                    RegionID = model.RegionID,
                    OrganizationID = model.OrganizationID,
                    DialogPartnerID = model.DialogPartnerID,
                    Name = model.Name.Trim(),
                    Description = (Session["fileGuidUpload"] == null) ? string.Empty : Session["fileGuidUpload"].ToString() + "/" + Session["fileNameUpload"].ToString()
                };
                CountryBOL.Insert(country);
            }
            return RedirectToAction("Index");
        }

        [HttpGet]
        public ActionResult Edit(int countryID)
        {
            var country = CountryBOL.GetCountryById(countryID);
            var region = RegionBOL.GetAllRegion();
            var organization = OrganizationBOL.GetAllOrganization();
            var dialogPartner = DialogPartnerBOL.GetAllDialogPartner();
            var model = new CountryViewModel
            {
                CreateAt = country.CreateAt,
                CreateBy = country.CreateBy,
                Description = country.Description,
                DialogPartnerID = country.DialogPartnerID,
                ID = country.ID,
                Name = country.Name.Trim(),
                OrganizationID = country.OrganizationID,
                RegionID = country.RegionID,
                Region = new SelectList(region, "ID", "Name"),
                Organization = new SelectList(organization, "ID", "Name"),
                DialogPartner = new SelectList(dialogPartner, "ID", "Name")
            };
            if (!string.IsNullOrEmpty(model.Description))
            {
                string[] _strPath = model.Description.Split('/');
                Session["fileGuidUpload"] = _strPath[0];
                Session["fileNameUpload"] = _strPath[1];
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult Edit(CountryViewModel model)
        {
            if (ModelState.IsValid)
            {
                Country country = new Country
                {
                    RegionID = model.RegionID,
                    OrganizationID = model.OrganizationID,
                    DialogPartnerID = model.DialogPartnerID,
                    Name = model.Name.Trim(),
                    Description = (Session["fileGuidUpload"] == null) ? string.Empty : Session["fileGuidUpload"].ToString() + "/" + Session["fileNameUpload"].ToString(),
                    CreateAt = model.CreateAt,
                    CreateBy = model.CreateBy,
                    ID = model.ID
                };
                CountryBOL.Update(country);
            }
            //return View(model);
            return RedirectToAction("Index");
        }

        
        [AcceptVerbs(HttpVerbs.Post)]
        [GridAction]
        public ActionResult _DeleteAjaxEditing(int id)
        {
            //Find a customer with ProductID equal to the id action parameter            
            if (id > 0)
            {
                //Delete the record
                if (!CountryBOL.Delete(id))
                {
                    ModelState.AddModelError(String.Empty, @"This Country have city(ies). Please check again!");
                }
            }                        
            //Rebind the grid
            return View(new GridModel(CountryBOL.GetAllCountryJoin()));
        }

        public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
        {
            //if (Session["fileGuidUpload"] != null)
            //{
            //    var physicalPath = Path.Combine(Server.MapPath("~/Upload/" + Session["fileGuidUpload"].ToString()) + "/", Session["fileNameUpload"].ToString());
            //    if (System.IO.File.Exists(physicalPath))
            //    {
            //        // The files are not actually removed in this demo
            //        System.IO.File.Delete(physicalPath);
            //        // Delete folder
            //        var path = Server.MapPath("~/Upload/" + Session["fileGuidUpload"].ToString());
            //        Directory.Delete(path);
            //        Session["fileGuidUpload"] = null;
            //        Session["fileNameUpload"] = null;
            //    }
            //}

            // The Name of the Upload component is "attachments" 
            foreach (var file in attachments)
            {
                // Create random folder
                Guid stringFolder = Guid.NewGuid();
                var path = Server.MapPath("~/Upload/" + stringFolder.ToString());
                Directory.CreateDirectory(path);

                // Some browsers send file names with full path. This needs to be stripped.
                var fileName = Path.GetFileName(file.FileName);
                var physicalPath = Path.Combine(Server.MapPath("~/Upload/" + stringFolder.ToString() + "/"), fileName);

                // The files are not actually saved in this demo
                file.SaveAs(physicalPath);
                Session["fileGuidUpload"] = stringFolder;
                Session["fileNameUpload"] = file.FileName;
            }
            // Return an empty string to signify success
            return Content("");
        }
        public ActionResult Remove(string[] fileNames)
        {
            // The parameter of the Remove action must be called "fileNames"
            foreach (var fullName in fileNames)
            {
                var fileName = Path.GetFileName(fullName);
                var physicalPath = Path.Combine(Server.MapPath("~/Upload/" + Session["fileGuidUpload"].ToString()) + "/", fileName);

                // TODO: Verify user permissions
                if (System.IO.File.Exists(physicalPath))
                {
                    // The files are not actually removed in this demo
                     System.IO.File.Delete(physicalPath);
                    // Delete folder
                     var path = Server.MapPath("~/Upload/" + Session["fileGuidUpload"].ToString());
                     Directory.Delete(path);
                     Session["fileGuidUpload"] = null;
                     Session["fileNameUpload"] = null;
                }
            }
            // Return an empty string to signify success
            return Content("");
        }

    }
}
